import React, { FC, useEffect } from 'react';
import { Modal, Form, InputNumber, Input, Select } from 'antd';
import { PersonAccountItem } from '@/services/person/account';

interface DebtProps {
  visible: boolean;
  personAccountItem: Partial<PersonAccountItem> | undefined;
  onSubmit: (values: PersonAccountItem) => void;
  onCancel: () => void;
}

const formLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 13 },
};

const DebtForm: FC<DebtProps> = (props) => {
  const [form] = Form.useForm();
  const { visible, personAccountItem, onCancel, onSubmit } = props;

  useEffect(() => {
    if (form && !visible) {
      form.resetFields();
    }
  }, []);

  useEffect(() => {
    if (personAccountItem) {
      form.setFieldsValue({
        ...personAccountItem,
        accountType: 'debt',
      });
    } else {
      form.setFieldsValue({
        accountType: 'debt',
      });
    }
  }, [props.personAccountItem]);

  const handleSubmit = () => {
    if (!form) return;
    form.submit();
  };

  const handleFinish = (values: { [key: string]: any }) => {
    if (onSubmit) {
      onSubmit({ ...values, accountType: 'debt' } as PersonAccountItem);
    }
  };

  const modalFooter = { okText: '保存', onOk: handleSubmit, onCancel };

  const renderContent = () => {
    return (
      <>
        <Form.Item
          label="出借人"
          name="accountName"
          rules={[{ required: true, message: '请输入出借人' }]}
        >
          <Input placeholder="请输入出借人" />
        </Form.Item>
        <Form.Item
          label="借入金额"
          name="inAmount"
          rules={[{ required: true, message: '请输入借入金额' }]}
        >
          <InputNumber
            style={{ width: '100%' }}
            step={1000}
            formatter={(value) => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
            placeholder="请输入借入金额"
          />
        </Form.Item>
        <Form.Item label="已还金额" 
          name="outAmount"
          >
          <InputNumber
            style={{ width: '100%' }}
            step={1000}
            formatter={(value) => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
            placeholder="请输入已还金额"
          />
        </Form.Item>
        <Form.Item label="备注" name="remark">
          <Input.TextArea rows={4} placeholder="请输入备注" />
        </Form.Item>
        <Form.Item hidden={true} name="id">
          <Input hidden={true} />
        </Form.Item>
      </>
    );
  };

  return (
    <Modal
      title={`债务账户 添加`}
      width={640}
      destroyOnClose
      open={visible}
      {...modalFooter}
    >
      <Form {...formLayout} form={form} onFinish={handleFinish}>
        {renderContent()}
      </Form>
    </Modal>
  );
};

export default DebtForm;